from Selenium2Library.keywords.keywordgroup import KeywordGroup
import time
import datetime
from Selenium2Library.locators import ElementFinder

class _BreezeKeywords(KeywordGroup):
    """Library for Breeze Keywords purposes.
    
    This library is used in Breeze projects.
    """
    def __init__(self):
        """Does nothing. init only"""
        print '_BreezeKeywords.__init__'
        
    def select_frame(self, locator):
        """Sets frame identified by `locator` as current frame.

        Key attributes for frames are `id` and `name.` See `introduction` for
        details about locating elements.
        """
        self._info("Selecting frame '%s'." % locator)
        element = self._element_find(locator, True, True, tag='frame')
        self._current_browser().switch_to_frame(element)
        
    def select_iframe(self, locator):
        """Sets frame identified by `locator` as current frame.

        Key attributes for frames are `id` and `name.` See `introduction` for
        details about locating elements.
        """
        self._info("Selecting frame '%s'." % locator)
        element = self._element_find(locator, True, True, tag='iframe')
        self._current_browser().switch_to_frame(element)
    
        
    def select_top_frame_ibanking(self):
        '''Used for ID iBanking to select to top frame
        '''
        self._current_browser().switch_to_default_content()
        self.select_frame("//frame[@id='CenterContent']")
        self.select_iframe("//iframe[@id='iframename']")
        self.select_frame("//frame[@id='loginFrame']")
        self.select_frame("//frame[@name='loginTopFrame']")

    def select_links_frame_ibanking(self):
        """Used for ID iBanking to select to links frame which is at right side.
        Navigation bar.
        """
        self._current_browser().switch_to_default_content()
        self.select_frame("//frame[@id='CenterContent']")
        self.select_iframe("//iframe[@id='iframename']")
        self.select_frame("//frame[@id='loginlinksFrame']")
        
    def read_bmw_accounts(self):
        """Read BMW Accounts list for comparing with Accounts in Ibanking.
        
        See `Read Ibnk Accounts`
        
        "See" list comparing.
        """
        return self._run('read_bmw_accounts')

    def _read_bmw_accounts_hk(self):
        ''' Return a list of all accounts, cards and loans from BMW.
        '''
        names = self._element_find("//div[@id='main']/div/dl/dd/a/span[1]", False, False)
        numbers = self._element_find("//div[@id='main']/div/dl/dd/a/span[2]", False, False)
        amounts = self._element_find("//div[@id='main']/div/dl/dd/a/span[3]", False, False)
        
        accounts = []
        for i in xrange(len(names)): #TODO
            accounts.append([names[i].text,
                             numbers[i].text.split(' ')[0],
                             amounts[i].text[:3],
                             amounts[i].text[3:]])
        self._info(len(accounts))
        return accounts

    def _read_bmw_accounts_pk(self):
        names = self._element_find("//div[@id='main']/div/dl/dd/a/span[1]", False, False)
        numbers = self._element_find("//div[@id='main']/div/dl/dd/a/span[2]", False, False)
        amounts = self._element_find("//div[@id='main']/div/dl/dd/a/span[3]", False, False)
        
        accounts = []
        for i in xrange(len(names)): #TODO
            accounts.append([names[i].text,
                            numbers[i].text,
                            amounts[i].text[:3],
                            amounts[i].text[3:]])
        self._info(len(accounts))
        return accounts

    def _read_bmw_accounts_id(self):
        '''For BMW ID, please refer to BMW PK if not work here
        '''
        names = self._element_find("//div[@id='main']/div/dl/dd/a/span[1]", False, False)
        numbers = self._element_find("//div[@id='main']/div/dl/dd/a/span[2]", False, False)
        amounts = self._element_find("//div[@id='main']/div/dl/dd/a/span[3]", False, False)
        
        accounts = []
        for i in xrange(len(names)): #TODO
            accounts.append([names[i].text,
                            numbers[i].text,
                            amounts[i].text[:3],
                            amounts[i].text[3:]])
        self._info(len(accounts))
        return accounts
    
    def read_ibnk_accounts(self):
        """Read iBanking Accounts list for comparing with Accounts in BMW.
        
        See `Read BMW Accounts`
        
        "See" list comparing.
        """
        return self._run('read_ibnk_accounts')

    def _read_ibnk_accounts_hk(self):
        ''' Return a list of all accounts, cards and loans from iBanking.
        '''
        rows = self._element_find("//table[@class='tbl_listing']/tbody/tr[@class='tbl_listing_row_even' or @class='tbl_listing_row_odd']", False, False)
        
        accounts = []
        for r in rows: #TODO
            name = r.find_elements_by_xpath("./td[2]/a")
            number = r.find_elements_by_xpath("./td[3]")
            currencie = r.find_elements_by_xpath("./td[4]")
            curr_bal = r.find_elements_by_xpath("./td[5]")
            ava_bal = r.find_elements_by_xpath("./td[7]")
            self._info('%s> %s>' % (ava_bal[0].text[:-3], curr_bal[0].text[:-3]))
            if not ava_bal[0].text[:-3].strip() == '':
                balance = ava_bal[0].text[:-3].strip()
            else:
                balance = curr_bal[0].text[:-3].strip()
            accounts.append([name[0].text,
                             number[0].text,
                             currencie[0].text.strip(),
                             balance])
        self._info(len(accounts))
        return accounts
         
    def _read_ibnk_accounts_pk(self):
        ''' Return a list of all accounts, cards and loans from iBanking.
        '''
        rows = self._element_find("//table[@class='tbl_listing']", False, False)

        accountlist = []
        cardlist = []
        loanlist = []
        accounts = []
        
        for r in rows: #TODO
            if r.find_elements_by_xpath("./tbody/tr[1]/th[2]")[0].text == 'Accounts':
                accountlist = r.find_elements_by_xpath("./tbody/tr[@class='tbl_listing_bottom']")
            if r.find_elements_by_xpath("./tbody/tr[1]/th[2]")[0].text == 'Cards':
                cardlist = r.find_elements_by_xpath("./tbody/tr[position()>1 and position()<last()]")
            if r.find_elements_by_xpath("./tbody/tr[1]/th[2]")[0].text == 'Loans & Saadiq Finance':
                loanlist = r.find_elements_by_xpath("./tbody/tr[position()>1 and position()<last()-1]")
        
        for r in accountlist: #get accounts list
            name = r.find_elements_by_xpath("./td[2]/a")
            number = r.find_elements_by_xpath("./td[3]/a")
            currencie = r.find_elements_by_xpath("./td[4]")
            curr_bal = r.find_elements_by_xpath("./td[7]")
            ava_bal = r.find_elements_by_xpath("./td[5]")
            if not curr_bal[0].text[:-3].strip() == '':
                balance = curr_bal[0].text[:-3].strip()
            else:
                balance = ava_bal[0].text[:-3].strip()
            accounts.append([name[0].text,
                             number[0].text,
                             currencie[0].text.strip(),
                             balance])
        for r2 in cardlist: #get cards list
            name = r2.find_elements_by_xpath("./td[2]/a")
            number = r2.find_elements_by_xpath("./td[3]/a")
            currencie = r2.find_elements_by_xpath("./td[4]")
            balance = r2.find_elements_by_xpath("./td[5]")[0].text[4:-3]
            accounts.append([name[0].text,
                            number[0].text,
                            currencie[0].text.strip(),
                            balance])
        for r3 in loanlist: #get loans list
            name = r3.find_elements_by_xpath("./td[2]/a")
            number = r3.find_elements_by_xpath("./td[3]/a")
            currencie = r3.find_elements_by_xpath("./td[4]")[0].text[:3]
            balance = r3.find_elements_by_xpath("./td[4]")[0].text[4:-3]
            accounts.append([name[0].text,
                            number[0].text,
                            currencie,
                            balance])
        self._info(len(accounts))
        return accounts

    def _read_ibnk_accounts_id(self):
        #select to links frame for clicking "Accounts" hyperlink to see Accounts list
        self.select_links_frame_ibanking()
        self.current_frame_contains("Accounts")
        
        element = self._element_find("//a[@id='nav_ML4']", True, False)
        self._info(element)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Please click on \"Account Number\" to view details.")
        
        rows = self._element_find("//*[@id='acclist']/tbody/tr", False, False)
        self._info(rows)
        
        accounts = []
        
        #accounts records
        for r in rows: #TODO
            type = r.find_elements_by_xpath("./td[1]")
            number = r.find_elements_by_xpath("./td[2]")
            avail = r.find_elements_by_xpath("./td[3]")
            ledger = r.find_elements_by_xpath("./td[4]")
            self._info('%s> %s> %s> %s>' % (type[0].text, number[0].text, avail[0].text, ledger[0].text))
            
            accounts.append([type[0].text,
                             number[0].text,
                             ledger[0].text.split(' ')[1],
                             ledger[0].text.split(' ')[2]])
        self._info(len(accounts))
        
        #credit cards records
        self.select_links_frame_ibanking()
        element = self._element_find("//*[@id='nav_ML300']", True, False)
        self._info(element)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Credit Cards")
        
        rows2 = self._element_find("//tr[@class='table_row_white']", False, False)
        for r2 in rows2: #TODO
            type = r2.find_elements_by_xpath("./td[1]")
            number = r2.find_elements_by_xpath("./td[2]")
            bonus = r2.find_elements_by_xpath("./td[3]")

            self._info('%s> %s> %s>' % (type[0].text, number[0].text, bonus[0].text))
            #balance = r2.find_elements_by_xpath("./td[5]")[0].text[4:-3]
            accounts.append([type[0].text,
                            number[0].text,
                            bonus[0].text.strip()])
        self._info(len(accounts))
        
        #do not implement "Loan" part as no data when writing script.
        
        return accounts

    def read_ibnk_accounts_count(self):
        """Used in transaction-list.tsv it is used for transaction list of an account/card comparing between BMW and iBanking.
        
        First compare the first account then compare the first card.
        
        Count the number of accounts in ibanking and used this number to calculate position of card and read card in BMW for comparing.
        """
        return self._run('read_ibnk_accounts_count')
    
    def _read_ibnk_accounts_count_pk(self):
        '''Find no of accounts and then use this number to find the first credit card record in BMW for credit card transaction comparing.
        '''
        rows = self._element_find("//table[@class='tbl_listing']", False, False)

        accountlist = []
        
        for r in rows: #TODO
            if r.find_elements_by_xpath("./tbody/tr[1]/th[2]")[0].text == 'Accounts':
                accountlist = r.find_elements_by_xpath("./tbody/tr[@class='tbl_listing_bottom']")
        self._info(len(accountlist))
        return int(len(accountlist))
    
    def _read_ibnk_accounts_count_id(self):
        '''Find no of accounts and then use this number to find the first credit card record in BMW for credit card transaction comparing.
        '''
        self.select_links_frame_ibanking()
        self.current_frame_contains("Accounts")
        
        element = self._element_find("//a[@id='nav_ML4']", True, False)
        self._info(element)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Please click on \"Account Number\" to view details.")
        
        rows = self._element_find("//*[@id='acclist']/tbody/tr", False, False)
        self._info(rows)
        return len(rows)
            
    def read_bmw_transaction(self):
        """Used in transaction-list.tsv it is used for transaction list of an accountcomparing between BMW and iBanking.
        
        This keyword is used for read the transaction list of account in BMW.
        
        See `Read BMW Card Transaction`, `Read Ibnk Account Transaction` and `Read Ibnk Card Transaction`
        """
        return self._run('read_bmw_transaction')

    def _read_bmw_transaction_pk(self):
  
        countdate = self.get_matching_xpath_count("//div[@class='list-view']/dl/dt[@id]")
        #self._info(countdate)
        counttrans = self.get_matching_xpath_count("//div[@class='list-view']/dl/dd[@id]")
        #self._info(counttrans)
        
        name = self._element_find("//div[@class='list-view']/dl/dd/a/span[@class='info-primary']", False, False)
        balance = self._element_find("//div[@class='list-view']/dl/dd/a/span[2] ", False, False)
        date = self._element_find("//div[@class='list-view']/dl/dd[@id]", False, False)
         
        accounts = []
        for i in xrange(len(name)): #TODO
            date1 = self.get_element_attr(date[i], "id").split(":")[0]
            
            #2011-10-01 to 01/10/2011
            year = date1.split("-")[0]
            month = date1.split("-")[1]
            day = date1.split("-")[2]
            
            #here the "if" condition is try to only append the immediate transaction to accounts as scheduled transaction records cannot match with them on ibanking.
            #if the issue resolved, we can uncomment "read scheduled transactions if any." part in read_ibnk_account_transaction
            if int(year) <= 2011 and int(month) <= 10 and int(day) <= 01:
                date1 = day + "/" + month + "/" + year + " "
                self._info(date1 + "-" + name[i].text + "-" + balance[i].text)
                accounts.append([name[i].text,
                                balance[i].text,
                                date1])
            else:
                pass
                            
        self._info(len(accounts)) 
        return accounts

    def _read_bmw_transaction_id(self):
        '''For BMW ID, please refer to BMW PK if not work here
        '''  
        countdate = self.get_matching_xpath_count("//div[@class='list-view']/dl/dt[@id]")
        #self._info(countdate)
        counttrans = self.get_matching_xpath_count("//div[@class='list-view']/dl/dd[@id]")
        #self._info(counttrans)
        
        name = self._element_find("//div[@class='list-view']/dl/dd/a/span[@class='info-primary']", False, False)
        balance = self._element_find("//div[@class='list-view']/dl/dd/a/span[2] ", False, False)
        date = self._element_find("//div[@class='list-view']/dl/dd[@id]", False, False)
         
        accounts = []
        for i in xrange(len(name)): #TODO
            self._info(self.get_element_attr(date[i], "id") + "-" + name[i].text + "-" + balance[i].text)
            accounts.append([name[i].text,
                            balance[i].text,
                            self.get_element_attr(date[i], "id")])

        self._info(len(accounts))
        return accounts

    def read_bmw_card_transaction(self):
        """Used in transaction-list.tsv it is used for transaction list of a card comparing between BMW and iBanking.
        
        This keyword is used for read the transaction list of card in BMW.
        
        See `Read BMW Transaction`, `Read Ibnk Account Transaction` and `Read Ibnk Card Transaction`
        """
        return self._run('read_bmw_card_transaction')

    def _read_bmw_card_transaction_pk(self):
  
        countdate = self.get_matching_xpath_count("//div[@class='list-view']/dl/dt[@id]")
        counttrans = self.get_matching_xpath_count("//div[@class='list-view']/dl/dd[@id]")
        
        name = self._element_find("//div[@class='list-view']/dl/dd/a/span[@class='info-primary']", False, False)
        balance = self._element_find("//div[@class='list-view']/dl/dd/a/span[2] ", False, False)
        date = self._element_find("//div[@class='list-view']/dl/dd[@id]", False, False)
         
        accounts = []
        for i in xrange(len(name)): #TODO
            date1 = self.get_element_attr(date[i], "id").split(":")[0]
            
            #2011-10-01 to 01/10/2011
            year = date1.split("-")[0]
            month = date1.split("-")[1]
            day = date1.split("-")[2]

            date1 = day + "/" + month + "/" + year + " "
            self._info(date1 + "-" + name[i].text + "-" + balance[i].text)
            accounts.append([name[i].text,
                            balance[i].text,
                            date1])
                            
        self._info(len(accounts)) 
        return accounts

    def _read_bmw_card_transaction_id(self):
  
        countdate = self.get_matching_xpath_count("//div[@class='list-view']/dl/dt[@id]")
        counttrans = self.get_matching_xpath_count("//div[@class='list-view']/dl/dd[@id]")
        
        name = self._element_find("//div[@class='list-view']/dl/dd/a/span[@class='info-primary']", False, False)
        balance = self._element_find("//div[@class='list-view']/dl/dd/a/span[2] ", False, False)
        date = self._element_find("//div[@class='list-view']/dl/dd[@id]", False, False)
         
        accounts = []
        for i in xrange(len(name)): #TODO
            date1 = self.get_element_attr(date[i], "id").split(":")[0]
            
            #2011-10-01 to 01/10/2011
            year = date1.split("-")[0]
            month = date1.split("-")[1]
            day = date1.split("-")[2]

            date1 = day + "/" + month + "/" + year + " "
            self._info(date1 + "-" + name[i].text + "-" + balance[i].text)
            accounts.append([name[i].text,
                            balance[i].text,
                            date1])
                            
        self._info(len(accounts)) 
        return accounts
        
    def read_ibnk_account_transaction(self):
        """Used in transaction-list.tsv it is used for transaction list of an account/card comparing between BMW and iBanking.
        
        This keyword is used for read the account transaction list in Ibanking.
        
        See `Read BMW Transaction` and `Read Ibnk Card Transaction`
        """
        return self._run('read_ibnk_account_transaction')
    
    def _read_ibnk_account_transaction_pk(self):   
        transactions1 = []
        temp = [] 
               
#        ##read scheduled transactions if any. cannot be used now, as the data do not match with BMW. said that it is ibanking's bug,need confirming
#        element = self._element_find("//*[@id='parentMenuHead'][6]/a/table/tbody/tr/td", True, False)
#        element.click()
#        self.wait_until_page_contains("Funds Transfer Between Own Accounts")
#        
#        element = self._element_find("//*[@id='parentMenuContentSelected']/div[3]/a/table/tbody/tr/td", True, False)
#        self._info(element.text)
#        element.click()
#        self.wait_until_page_contains("Filter your transactions so that the list is more relevant to your search")
#
#        #total page for transaction records Total: 44,1 of 3 page(s).
#        if self._is_text_present("No Transaction Available"):
#            self._info("No Beneficiaries Available IFT")
#        else:
#            element = self._element_find("//table[@class='pagebanner']/tbody/tr/td", False, False)#Total: 3, 1 of 1 page(s).
#            pagecount = element[0].text.split(" ")[4]
#            
#            rows4 = self._element_find("//*[@id='transferHistoryList']/tbody/tr", False, False)
#            self._info(len(rows4))
#            
#            if int(pagecount) > 1:
#                temp = (self._read_ibnk_account_scheduled_transaction_pk_single_page(rows4, len(rows4)))
#                transactions1 = transactions1 + temp
#                
#                for k in range(1, int(pagecount)):
#                    if k == 1:
#                        element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[" + str(k) + "]", True, False)
#                    else:
#                        element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[" + str(k + 2) + "]", True, False)
#                    element.click()
#                    self.wait_until_page_contains(str(k + 1) + " of " + str(pagecount) + " page(s).")
#                    
#                    rows4 = self._element_find("//*[@id='transferHistoryList']/tbody/tr", False, False)
#                    temp = (self._read_ibnk_account_scheduled_transaction_pk_single_page(rows4, len(rows4)))
#                    transactions1 = transactions1 + temp
#                
#            elif int(pagecount) == 1:
#                temp = (self._read_ibnk_account_scheduled_transaction_pk_single_page(rows4, len(rows4)))
#                transactions1 = transactions1 + temp
#            else:
#                pass
            
        #read account transaction history 
#        element = self._element_find("//*[@id='parentMenuHead']/a", True, False)
#        element.click()
#        self.wait_until_page_contains("You last logged in at")
        
        #click to show the first account's transaction
        element = self._element_find("//*[@id='printContent']/table/tbody/tr[5]/td[1]/table[1]/tbody/tr[2]/td[2]/a", True, False)
        self._info(element)
        element.click()
        self.wait_until_page_contains("Account transactions shown")

        if self._is_text_present("No transactions to display"):
            self._info("No transactions to display for account")
        else:
            #find page no for the transaction
            element = self._element_find("//*[@id='printContent']/table[2]/tbody/tr/td", False, False)
            self._info(element[0].text)
            
            #total page for transaction records Total: 44,1 of 3 page(s).
            pagecount = element[0].text.split(" ")[3]
            
            rows4 = self._element_find("//*[@id='vAcctTrxnList']/tbody/tr", False, False)
            self._info(len(rows4))

            #read transaction records in each page
            if int(pagecount) > 1:
                temp = (self._read_ibnk_account_transaction_pk_single_page(rows4, len(rows4)))
                transactions1 = transactions1 + temp
                
                for k in range(1, int(pagecount)):
                    if k == 1:
                        element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[" + str(k) + "]", True, False)
                    elif k < 4:
                        element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[" + str(k + 2) + "]", True, False)
                    else:
                        element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[6]", True, False)
                    element.click()
                    self.wait_until_page_contains(str(k + 1) + " of " + str(pagecount) + " page(s).")
                    
                    rows4 = self._element_find("//*[@id='vAcctTrxnList']/tbody/tr", False, False)
                    temp = (self._read_ibnk_account_transaction_pk_single_page(rows4, len(rows4)))
                    transactions1 = transactions1 + temp
                
            elif int(pagecount) == 1:
                temp = (self._read_ibnk_account_transaction_pk_single_page(rows4, len(rows4) - 1))
                transactions1 = transactions1 + temp
            else:
                pass
                  
        return transactions1

    def _read_ibnk_account_transaction_pk_single_page(self, rows, num):
        transactions = []
    
        for i in range(0, num): #TODO
            date = rows[i].find_elements_by_xpath("./td[1]")
            description = rows[i].find_elements_by_xpath("./td[2]")
            withdrawal = rows[i].find_elements_by_xpath("./td[5]")
            deposit = rows[i].find_elements_by_xpath("./td[4]")
            amountPKR = rows[i].find_elements_by_xpath("./td[6]")
            self._info('%s> %s> %s> %s> %s>' % (date[0].text, description[0].text, withdrawal[0].text, deposit[0].text, amountPKR[0].text))
            
            if withdrawal[0].text.strip() == '':
                transactions.append([description[0].text,
                                    "PKR" + deposit[0].text.strip(),
                                    date[0].text])
            else:
                transactions.append([description[0].text,
                                    "PKR" + withdrawal[0].text.strip(),
                                    date[0].text])
        self._info(len(transactions))
        
        return transactions

    def _read_ibnk_account_scheduled_transaction_pk_single_page(self, rows, num):
        transactions = []
    
        for i in range(0, num): #TODO
            date = rows[i].find_elements_by_xpath("./td[1]")
            description = rows[i].find_elements_by_xpath("./td[6]")#Transafer Type
            amount = rows[i].find_elements_by_xpath("./td[5]")
            fromaccount = rows[i].find_elements_by_xpath("./td[2]")
            toaccount = rows[i].find_elements_by_xpath("./td[3]")
            beneficiary = rows[i].find_elements_by_xpath("./td[4]")
            
            transactions.append([description[0].text,
                                "PKR" + amount[0].text.split(" ")[1].strip(),
                                date[0].text])
        self._info(len(transactions))
        
        return transactions
            
    def _read_ibnk_account_transaction_id(self):
        self.select_links_frame_ibanking()
        self.current_frame_contains("Accounts")
        
        #click "Accounts" link in left navigation bar
        element = self._element_find("//a[@id='nav_ML4']", True, False)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Please click on \"Account Number\" to view details.")
        
        #click to show the first account's transaction
        element = self._element_find("//*[@id='acclist']/tbody/tr[1]/td[2]", True, False)
        element.click()
        self.wait_until_page_contains("Account Transaction Details")
        
        #click dropdown button
        element = self._element_find("//*[@id='pagePrintTag']/table/tbody/tr[1]/td/table/tbody/tr[6]/td[3]/select[2]", True, False)
        element.click()
        
        #click to set a month
        self._info(datetime.datetime.now())
        self._info(str(datetime.datetime.now()).split("-")[1])
        self._info(int(str(datetime.datetime.now()).split("-")[1]))
        
        month = int(str(datetime.datetime.now()).split("-")[1]) - 2
        self._info(int(str(datetime.datetime.now()).split("-")[1]) - 2)
        element = self._element_find("//*[@id='pagePrintTag']/table/tbody/tr[1]/td/table/tbody/tr[6]/td[3]/select[2]/option[" + str(month) + "]", True, False)
        self._info(element.text)
        element.click()
        
        #click the show button
        element = self._element_find("//*[@id='pagePrintTag']/table/tbody/tr[1]/td/table/tbody/tr[8]/td[4]/table/tbody/tr/td/a/span", True, False)
        element.click()
        
        self.wait_until_page_contains("OPENING BALANCE")
        
        #find page no for the transaction
        element = self._element_find("//*[@id='pagePrintTag']/table/tbody/tr[8]/td/table/tbody/tr/td[2]/span/b", False, False)
        self._info(element[0].text)
        
        #total page for transaction records
        pagecount = element[0].text.split(" ")[3]
        self._info(pagecount)

        rows4 = self._element_find("//div[@id='pagePrintTag']/table/tbody/tr[4]/td/table/tbody/tr[@class='table_row_white' or @class='table_row_grey']", False, False)
        self._info(len(rows4))
            
        transactions1 = []
        
        #read the transaction record in each page. if not work here, please refer to "_read_ibnk_account_transaction_pk" as there is finished.
        #but please note, cannot copy directly, as there is slight difference between ID and PK  
        #mainly page number format and actual argument for single page call      
        if int(pagecount) > 1:
            transactions1.append([self._read_ibnk_account_transaction_id_single_page(rows4, len(rows4))])
            for k in range(1, int(pagecount)):
                element = self._element_find("//*[@id='Tip1']/a[" + str(k + 1) + "]", True, False)
                self._info(element)
                self._info(element.text)
                element.click()
                self.wait_until_page_contains("Page  " + str(k + 1) + " of " + str(pagecount))
                if k == int(pagecount) - 1:#need to not to loop the last line, as there is no transaction in this line, the index will out of range if do not minus the last line in last page
                    rows4 = self._element_find("//div[@id='pagePrintTag']/table/tbody/tr[4]/td/table/tbody/tr[@class='table_row_white' or @class='table_row_grey']", False, False)
                    transactions1.append([self._read_ibnk_account_transaction_id_single_page(rows4, len(rows4) - 1)])
                else:
                    rows4 = self._element_find("//div[@id='pagePrintTag']/table/tbody/tr[4]/td/table/tbody/tr[@class='table_row_white' or @class='table_row_grey']", False, False)
                    transactions1.append([self._read_ibnk_account_transaction_id_single_page(rows4, len(rows4))])                    
        elif int(pagecount) == 1:
            transactions1.append([self._read_ibnk_account_transaction_id_single_page(rows4, len(rows4) - 1)])
        else:
            pass
        return transactions1
    
    def _read_ibnk_account_transaction_id_single_page(self, rows, num):
        transactions = []
    
        for i in range(2, num): #TODO
            date = rows[i].find_elements_by_xpath("./td[2]")
            description = rows[i].find_elements_by_xpath("./td[4]")
            withdrawal = rows[i].find_elements_by_xpath("./td[5]")
            deposit = rows[i].find_elements_by_xpath("./td[7]")
            amountIDR = rows[i].find_elements_by_xpath("./td[8]")
            self._info('%s> %s> %s> %s> %s>' % (date[0].text, description[0].text, withdrawal[0].text, deposit[0].text, amountIDR[0].text))
                    
            transactions.append([description[0].text,
                                amountIDR[0].text,
                                date[0].text])
        self._info(len(transactions))
        
        return transactions

    def read_ibnk_card_transaction(self):
        """Used in transaction-list.tsv it is used for transaction list of an account/card comparing between BMW and iBanking.
        
        This keyword is used for read the card transaction list in Ibanking.
        
        See `Read BMW Transaction` and `Read Ibnk Account Transaction`
        """
        return self._run('read_ibnk_card_transaction')
    
    def _read_ibnk_card_transaction_pk(self):
#        element = self._element_find("//*[@id='parentMenuHead']/a", True, False)
#        element.click()
#        self.wait_until_page_contains("You last logged in at")
        
        #click to show the first card's transaction
        element = self._element_find("//*[@id='parentMenuHead'][2]/a/table/tbody/tr/td", True, False)
        self._info(element)
        element.click()
        self.wait_until_page_contains("Cards Summary")
        
        element = self._element_find("//*[@id='parentMenuContentSelected']/div[2]/a/table/tbody/tr/td", True, False)
        self._info(element)
        element.click()
        self.wait_until_page_contains("Select Card:")
        
        '''Drop down list selection for past 90 days select, please refer to _read_ibnk_account_transaction_id
        '''
        
#        if No transactions to display
        #find page no for the transaction
        element = self._element_find("//*[@id='printContent']/table[2]/tbody/tr/td", False, False)
        self._info(element[0].text)
        
        #total page for transaction records Total: 24,1 of 2 page(s)..
        pagecount = element[0].text.split(" ")[3]
        self._info(pagecount)

        transactions1 = list()   
        temp = list()        

        rows4 = self._element_find("//*[@id='cardTransactionVO']/tbody/tr", False, False)
        self._info(len(rows4))
                   
        if int(pagecount) > 1:
            temp = (self._read_ibnk_card_transaction_pk_single_page(rows4, len(rows4), 0))
            transactions1 = transactions1 + temp
            for k in range(1, int(pagecount)):
                if k == 1:
                    element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[" + str(k) + "]", True, False)
                elif k < 4:
                    element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[" + str(k + 2) + "]", True, False)
                else:
                    element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[6]", True, False)
                element.click()
                self.wait_until_page_contains(str(k + 1) + " of " + str(pagecount) + " page(s).")
                
#                if k==int(pagecount)-1:#need to not to loop the last line of last page, as there is no transaction in this line, the index will out of range if do not minus the last line in last page
#                    rows4 = self._element_find("//*[@id='vAcctTrxnList']/tbody/tr", False, False)
#                    transactions1.append([self._read_ibnk_card_transaction_pk_single_page(rows4,len(rows4)-1)])
#                else:
                rows4 = self._element_find("//*[@id='cardTransactionVO']/tbody/tr", False, False)
                temp = (self._read_ibnk_card_transaction_pk_single_page(rows4, len(rows4), 0))
                transactions1 = transactions1 + temp                    
        elif int(pagecount) == 1:
            temp = (self._read_ibnk_card_transaction_pk_single_page(rows4, len(rows4) - 1, 1))
            transactions1 = transactions1 + temp
        else:
            pass
        return transactions1

    def _read_ibnk_card_transaction_pk_single_page(self, rows, num, start):
        transactions = []
        #12/12    ONLINE CASH ADV     -     6.68 DR
        #when have time, need to implement "No transactions to display"
    
        for i in range(start, num): #TODO
            date = rows[i].find_elements_by_xpath("./td[1]")
            description = rows[i].find_elements_by_xpath("./td[2]")
#            withdrawal= rows[i].find_elements_by_xpath("./td[5]")
#            deposit= rows[i].find_elements_by_xpath("./td[4]")
            amountPKR = rows[i].find_elements_by_xpath("./td[4]")
            self._info('%s> %s> %s>' % (date[0].text, description[0].text, amountPKR[0].text))

            transactions.append([description[0].text,
                                "PKR" + amountPKR[0].text.split(" ")[0],
                                date[0].text])

        self._info(len(transactions))
        
        return transactions
             
    def _read_ibnk_card_transaction_id(self):
        self.select_links_frame_ibanking()
        self.current_frame_contains("Accounts")
        
        element = self._element_find("//*[@id='nav_ML300']", True, False)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Credit Cards")
        
        element = self._element_find("//tr[@class='table_row_white']/td[2]", True, False)
        element.click()
        self.wait_until_page_contains("Card Transaction Details")
        
        transactions = []

        #cards transactions. but here is only for one page. have not implemented the get card transaction for each page.
        #no paging data when writing this keyword. can refer to "_read_ibnk_account_transaction_pk" for read transaction for each page.
        rows3 = self._element_find("//td[@valign='top']/table[@id='accountsViewTable']/tbody/tr[@height='27px']", False, False)
        self._info(len(rows3))
        for i in range(1, len(rows3) - 1): #TODO
            date = rows3[i].find_elements_by_xpath("./td[1]")
            description = rows3[i].find_elements_by_xpath("./td[2]")
            currency = rows3[i].find_elements_by_xpath("./td[3]")
            amountIDR = rows3[i].find_elements_by_xpath("./td[5]")
            self._info(date[0].text)
            self._info(description[0].text)
            self._info(currency[0].text)
            self._info(amountIDR[0].text)
            
            transactions.append([description[0].text,
                            amountIDR[0].text,
                            date[0].text])
        self._info(len(transactions))
        return transactions
              
    def _read_ibnk_transaction_id_bak(self, accno):
        self.select_links_frame_ibanking()
        self.current_frame_contains("Accounts")
        
        element = self._element_find("//a[@id='nav_ML4']", True, False)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Please click on \"Account Number\" to view details.")
        
        rows = self._element_find("//*[@id='acclist']/tbody/tr", False, False)
        self._info(len(rows))
        accountno = len(rows)
        
        transactions = []
        
        if accno <= accountno:
            
            element = self._element_find("./td[2]", True, False)
            element.click()
            self.wait_until_page_contains("Transaction Details")
            
            #accounts transactions
            rows4 = self._element_find("//table[@id='accountsViewTable']/tbody/tr[@height='27px']", False, False)
            for r4 in rows4: #TODO
                date = r4.find_elements_by_xpath("./td[2]")
                description = r4.find_elements_by_xpath("./td[4]")
                withdrawal = r4.find_elements_by_xpath("./td[5]")
                deposit = r4.find_elements_by_xpath("./td[7]")
                amountIDR = r4.find_elements_by_xpath("./td[8]")
                self._info('%s> %s> %s> %s> %s>' % (date[0].text, description[0].text, withdrawal[0].text, deposit[0].text, amountIDR[0].txt))
                
                transactions.append([date[0].text,
                                 description[0].text,
                                 withdrawal[0].text.split(' ')[1],
                                 deposit[0].text.split(' ')[2],
                                 amountIDR[0].text.split(' ')[2], ])
            self._info(len(transactions))
        
        else:           
            self.select_links_frame_ibanking()
            element = self._element_find("//*[@id='nav_ML300']", True, False)
            element.click()
            self.select_top_frame_ibanking()
            self.wait_until_page_contains("Credit Cards")
            
            rows2 = self._element_find("//tr[@class='table_row_white']", False, False)
            cardno = len(rows2)
            if accno > (accountno + cardno):
                return null
            
            element = self._element_find("./td[2]", True, False)
            element.click()
            self.wait_until_page_contains("Transaction Details")

            #cards transactions
            rows3 = self._element_find("//table[@id='accountsViewTable']/tbody/tr[@height='27px']", False, False)
            for r3 in rows3: #TODO
                date = r3.find_elements_by_xpath("./td[1]")
                description = r3.find_elements_by_xpath("./td[2]")
                currency = r3.find_elements_by_xpath("./td[3]")
                amountIDR = r3.find_elements_by_xpath("./td[5]")
    
                self._info('%s> %s> %s>' % (date[0].text, description[0].text, currency[0].text, amountIDR[0].txt))
                transactions.append([date[0].text,
                                description[0].text,
                                currency[0].text.strip(),
                                amountIDR[0].txt])
            self._info(len(transactions))
            return transactions
                    
    def read_bmw_mail_list(self):
        """Used in mail.tsv it is used for mail comparing between BMW and iBanking.
        
        Comparing the mail count, unread mail and mail list.
        
        This keyword is used for read the mail list in BMW.
        
        See `Read Ibnk Mail List`
        """
        return self._run('read_bmw_mail_list')

    def _read_bmw_mail_list_pk(self):        
        rows4 = self._element_find("//dt[@id]", False, False)
        self._info(len(rows4))
        
        date = []
        for i in range(0, len(rows4)):
            date.append(self.get_element_attr(rows4[i], "id"))   
        self._info(date)
            
        j = len(rows4)
        #find the number of sibling children by reversed order    
        countdate = []
        for i in range(0, len(rows4)):
            rows3 = self._element_find("//dt[@id][" + str(j) + "]/following-sibling::dd/a/span", False, False)
            j = j - 1
            self._info(len(rows3))
            countdate.append(len(rows3))  
        self._info(countdate)
        
        #the no of records for each day
        countdate1 = []
        j = len(rows4)
        for i in range(0, len(rows4)):
            j = j - 1
            if j == 0:
                countdate1.append(countdate[j])
            else:
                countdate1.append(countdate[j] - countdate[j - 1])
        self._info(countdate1)
        
        #the begin record for each day
        countdate2 = []
        for i in range(0, len(rows4)):
            if i == 0:
                countdate2.append(countdate1[i])
            else:
                countdate2.append(countdate2[i - 1] + countdate1[i])
        self._info(countdate2)

        maillist = []
        rows3 = self._element_find("//dd[@id]", False, False)
        self._info(len(rows3))
        
        date1 = []
        j = 0
        k = 0        
        for i in range(0, len(rows3)): #TODO
            sub = rows3[i].find_elements_by_xpath("./a/span")
            read = rows3[i].find_elements_by_xpath("./a")
            
            k = k + 1
            if k <= countdate2[j]:                    
                date1 = date[j]
                self._info(date1)
            else:
                j = j + 1
                date1 = date[j]
                self._info(date1)
            
            #2012-10-02 target format is 01/10/2011
            year = date1.split("-")[0]
            month = date1.split("-")[1]
            day = date1.split("-")[2]
            self._info('%s> %s> %s>' % (sub[0].text, day + "/" + month + "/" + year, read[0].text))
            maillist.append([sub[0].text,
                            day + "/" + month + "/" + year,
                            self.get_element_attr(read[0], "class")])
        self._info(len(maillist))
        maillist.sort()
        return maillist

    def _read_bmw_mail_list_id(self):        
        rows4 = self._element_find("//dt[@id]", False, False)
        self._info(len(rows4))
        
        date = []
        for i in range(0, len(rows4)):
            date.append(self.get_element_attr(rows4[i], "id"))   
        self._info(date)
            
        j = len(rows4)
        #find the number of sibling children by reversed order    
        countdate = []
        for i in range(0, len(rows4)):
            rows3 = self._element_find("//dt[@id][" + str(j) + "]/following-sibling::dd/a/span", False, False)
            j = j - 1
            self._info(len(rows3))
            countdate.append(len(rows3))  
        self._info(countdate)
        
        #the no of records for each day
        countdate1 = []
        j = len(rows4)
        for i in range(0, len(rows4)):
            j = j - 1
            if j == 0:
                countdate1.append(countdate[j])
            else:
                countdate1.append(countdate[j] - countdate[j - 1])
        self._info(countdate1)
        
        #the begin record for each day
        countdate2 = []
        for i in range(0, len(rows4)):
            if i == 0:
                countdate2.append(countdate1[i])
            else:
                countdate2.append(countdate2[i - 1] + countdate1[i])
        self._info(countdate2)

        maillist = []
        rows3 = self._element_find("//dd[@id]", False, False)
        self._info(len(rows3))
        
        date1 = []
        j = 0
        k = 0        
        for i in range(0, len(rows3)): #TODO
            sub = rows3[i].find_elements_by_xpath("./a/span")
            read = rows3[i].find_elements_by_xpath("./a")
            
            k = k + 1
            if k <= countdate2[j]:                    
                date1 = date[j]
                self._info(date1)
            else:
                j = j + 1
                date1 = date[j]
                self._info(date1)
            
            #2012-10-02 target format is 01/10/2011
            year = date1.split("-")[0]
            month = date1.split("-")[1]
            day = date1.split("-")[2]
            self._info('%s> %s> %s>' % (sub[0].text, day + "/" + month + "/" + year, read[0].text))
            maillist.append([sub[0].text,
                            day + "/" + month + "/" + year,
                            self.get_element_attr(read[0], "class")])
        self._info(len(maillist))
        maillist.sort()
        return maillist
    
    def read_ibnk_mail_list(self):
        """Used in mail.tsv it is used for mail comparing between BMW and iBanking.
        
        Comparing the mail count, unread mail and mail list.
        
        This keyword is used for read the mail list in iBanking.
        
        See `Read BMW Mail List`
        """
        return self._run('read_ibnk_mail_list')

    def _read_ibnk_mail_list_pk(self):
        rows = self._element_find("//*[@id='mailForm']/table/tbody/tr[3]/td/table[3]/tbody/tr/td", False, False)
        self._info(len(rows))
        
#        Total: 35,1 of 2 page(s).
        mailpage = int((rows[0].text.split(",")[1]).split(" ")[2])
        self._info(mailpage)
        
        maillist1 = []
        
        rows3 = self._element_find("//*[@id='vMailList']/tbody/tr", False, False)
        self._info(len(rows3))
        
        temp = self._read_ibnk_mail_list_pk_single_page(rows3)
        maillist1 = maillist1 + temp

        if mailpage > 1:
            for i in range(1, mailpage):
                if i == 1:
                    element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[" + str(i) + "]", True, False)
                elif i < 4:
                    element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[" + str(i + 2) + "]", True, False)
                else:
                    element = self._element_find("//*[@id='ignorePrint_paging']/tbody/tr/td/a[6]", True, False)
                element.click()
                self.wait_until_page_contains("Mailbox")
                
                rows3 = self._element_find("//*[@id='vMailList']/tbody/tr", False, False)
                self._info(len(rows3))
                
                temp = self._read_ibnk_mail_list_pk_single_page(rows3)
                maillist1 = maillist1 + temp
            
            maillist1.sort()
            return maillist1
        else:
            maillist1.sort()
            return maillist1

    def _read_ibnk_mail_list_pk_single_page(self, rows3):
        maillist = []
        for i in range(0, len(rows3)): #TODO
            sub = rows3[i].find_elements_by_xpath("./td[4]")
            date = rows3[i].find_elements_by_xpath("./td[2]")
            read = rows3[i].find_elements_by_xpath("./td[3]")
#            unread = rows3[i].find_elements_by_xpath("./td[3]/b")
#                currency = rows3[i].find_elements_by_xpath("./td[2]")
            self._info('%s> %s>' % (sub[0].text, date[0].text))
            
            #array from 0;elements from 1
            if (self.get_matching_xpath_count("//*[@id='vMailList']/tbody/tr" + "[" + str(i + 1) + "]" + "/td[3]/b")) == str(1):
                maillist.append([sub[0].text,
                            date[0].text,
                            "message  unread"])                
            else:
                maillist.append([sub[0].text,
                            date[0].text,
                            "message"])

        return maillist
    
    def _read_ibnk_mail_list_id(self):
        '''To be implemented
        '''
        return true
    
    def read_ibnk_mail_count(self):
        """Used in mail.tsv it is used for mail comparing between BMW and iBanking.
        
        Comparing the mail count, unread mail and mail list.
        
        This keyword is used for read the mail count in iBanking.
        """
        return self._run('read_ibnk_mail_count')

    def _read_ibnk_mail_count_pk(self):
        element = self._element_find("//*[@id='ignorePrint_tbl_content_top']/div/table[3]/tbody/tr[3]/td[2]/a", True, False)
        element.click()
        self.wait_until_page_contains("Mailbox")
        
        rows3 = self._element_find("//*[@id='mailForm']/table/tbody/tr[3]/td/table[3]/tbody/tr/td", False, False)
        self._info(len(rows3))
        
        mailcount = ""
#        Total: 35,1 of 2 page(s).
        mailcount = (rows3[0].text.split(",")[0]).split(" ")[1]
        
        return mailcount

    def _read_ibnk_mail_count_id(self):
        '''To be implemented
        '''
        return true
        
    def read_ibnk_mail_unread_count(self):
        """Used in mail.tsv it is used for mail comparing between BMW and iBanking.
        
        Comparing the mail count, unread mail and mail list.
        
        This keyword is used for read the unread mail count in iBanking.
        """
        return self._run('read_ibnk_mail_unread_count')

    def _read_ibnk_mail_unread_count_pk(self):
  
        rows3 = self._element_find("//*[@id='ignorePrint_tbl_content_top']/div/table[3]/tbody/tr[2]/td[2]/span/span", False, False)
        self._info(len(rows3))
        
        self._info('%s> ' % (rows3[0].text.split(" ")[0]))
        return (rows3[0].text.split(" ")[0])

    def _read_ibnk_mail_unread_count_id(self):
        '''To be implemented
        '''
        return true    
    
    def read_bmw_payee(self):
        """Used in payee-list.tsv it is used for payee info comparing between BMW and iBanking. 
        Including the payee for Bill payment and IBFT(others).
        
        This keyword is used for reading payee in BMW. First read bill payment payee then read IBFT.
        
        See `Read Ibnk Payee`
        """
        return self._run('read_bmw_payee')
 
    def _read_bmw_payee_pk(self):
        #read bill payee
        payees = []
        
        if self._is_text_present("My Bills"):
            element = self._element_find("//*[@id='BP']/a", True, False)
            element.click()
            self.wait_until_page_contains_element("//dl[@class='heading collapsable']/dd[@style]/ul/li")

            rows3 = self._element_find("//dt[@id='BP']/following-sibling::dd/ul/li", False, False)
            self._info(len(rows3))
            
            for i in range(0, len(rows3)): #TODO
                account = rows3[i].find_elements_by_xpath("./a/span[3]")
                benefiname = rows3[i].find_elements_by_xpath("./a/span[1]")
                bankname = rows3[i].find_elements_by_xpath("./a/span[2]")
#                currency = rows3[i].find_elements_by_xpath("./a/span[3]")
                
                self._info('%s> %s> %s>' % (account[0].text.split(" ")[0].replace(",", ""), benefiname[0].text, bankname[0].text))
                payees.append([account[0].text.split(" ")[0].replace(",", ""),
                                benefiname[0].text,
                                bankname[0].text])
            self._info(len(payees))
        else:
            pass
        
        #read IBFT payee
        if self._is_text_present("Other Accounts"):
            element = self._element_find("//*[@id='IBFT']/a", True, False)
            element.click()
            self.wait_until_page_contains_element("//dt[@id='IBFT']/following-sibling::dd/ul/li")

            rows3 = self._element_find("//dt[@id='IBFT']/following-sibling::dd/ul/li", False, False)
            self._info(len(rows3))
            
            for i in range(0, len(rows3)): #TODO
                account = rows3[i].find_elements_by_xpath("./a/span[3]")
                benefiname = rows3[i].find_elements_by_xpath("./a/span[1]")
                bankname = rows3[i].find_elements_by_xpath("./a/span[2]")
#                currency = rows3[i].find_elements_by_xpath("./a/span[3]")
                
                self._info('%s> %s> %s>' % (account[0].text.split(" ")[0].replace(",", ""), benefiname[0].text, bankname[0].text))
                payees.append([account[0].text,
                                benefiname[0].text,
                                bankname[0].text])
            self._info(len(payees))
        else:
            pass
        
        payees.sort()
        return payees
   
    def _read_bmw_payee_id(self):
        '''For BMW ID, please refer to BMW PK if not work here
        '''
        if self._is_text_present("Other Accounts"):
            element = self._element_find("//*[@id='IBFT']/a", True, False)
            element.click()
            self.wait_until_page_contains_element("//dl[@class='heading collapsable']/dd[@style]/ul/li")

            payees = []
#            rows3 = self._element_find("//dt[@id='IBFT']/following-sibling::dd/ul/li[@id='7168138183635170786']", False, False)
            rows3 = self._element_find("//dt[@id='IBFT']/following-sibling::dd/ul/li", False, False)
            self._info(len(rows3))
#            self._info(self.get_element_attr(rows3[0], "id"))
            
            for i in range(0, len(rows3)): #TODO
                account = rows3[i].find_elements_by_xpath("./a/span[3]")
                benefiname = rows3[i].find_elements_by_xpath("./a/span[1]")
                bankname = rows3[i].find_elements_by_xpath("./a/span[2]")
                currency = rows3[i].find_elements_by_xpath("./a/span[3]")
                
                self._info('%s> %s> %s> %s>' % (account[0].text.split(" ")[0].replace(",", ""), benefiname[0].text, bankname[0].text, currency[0].text.split(" ")[1]))
                payees.append([account[0].text.split(" ")[0].replace(",", ""),
                                benefiname[0].text,
                                bankname[0].text,
                                currency[0].text.split(" ")[1]])
            self._info(len(payees))
            return payees
        else:
            return payees
        
    def read_ibnk_payee(self):
        """Used in payee-list.tsv it is used for payee info comparing between BMW and iBanking. 
        Including the payee for Bill payment and IBFT(others).
        
        This keyword is used for reading payee in iBanking. First read bill payment payee then read IBFT.
        
        See `Read BMW Payee`
        """
        return self._run('read_ibnk_payee')
    
    def _read_ibnk_payee_pk(self):
        #read bill payee
        element = self._element_find("//*[@id='parentMenuHead'][5]/a/table/tbody/tr/td", True, False)
        self._info(element.text)
        element.click()
        self.wait_until_page_contains("Pay a Registered Bill Payee ")
        
        rows3 = self._element_find("//table[@id='registerBillers']/tbody/tr", False, False)
        self._info(len(rows3))
        
        payees = []
        
        if self._is_text_present("No Beneficiaries Available"):
            self._info("No Beneficiaries Available IFT")
        else:
            for i in range(0, len(rows3)): #TODO
                account = rows3[i].find_elements_by_xpath("./td[2]")
                benefiname = rows3[i].find_elements_by_xpath("./td[1]")
                bankname = rows3[i].find_elements_by_xpath("./td[1]")
#                currency = rows3[i].find_elements_by_xpath("./td[2]")
                self._info('%s> %s> %s>' % (account[0].text, benefiname[0].text.split('-')[1], bankname[0].text.split('-')[0]))
                
                if len(bankname[0].text.split('-')) != 2:
                    self._info(bankname[0].text.split('-')[2])
                    payees.append([account[0].text,
                                    benefiname[0].text.split('-')[1] + "-" + benefiname[0].text.split('-')[2],
                                    bankname[0].text.split('-')[0]])                    
                else:
                    payees.append([account[0].text,
                                benefiname[0].text.split('-')[1],
                                bankname[0].text.split('-')[0]])
            self._info(len(payees))
            
        #read IBFT payee
        element = self._element_find("//*[@id='parentMenuHead'][7]/a/table/tbody/tr/td", True, False)
        element.click()
        self.wait_until_page_contains("Funds Transfer Between Own Accounts")
        
        element = self._element_find("//*[@id='parentMenuContentSelected']/div[2]/a/table/tbody/tr/td", True, False)
        self._info(element.text)
        element.click()
        self.wait_until_page_contains("Add Beneficiary")

        rows3 = self._element_find("//*[@id='vPayeeList']/tbody/tr", False, False)
        self._info(len(rows3))
        
        if self._is_text_present("No Beneficiaries Available"):
            self._info("No Beneficiaries Available IFT")
        else:
            for i in range(0, len(rows3)): #TODO
                account = rows3[i].find_elements_by_xpath("./td[2]")#PKR, 18960077001, STANDARD CHARTERED BANK
                benefiname = rows3[i].find_elements_by_xpath("./td[1]")
              
                payees.append([(account[0].text.split(',')[1].strip()+" "+account[0].text.split(',')[0]),
                            benefiname[0].text,
                            account[0].text.split(',')[2].strip()])
            self._info(len(payees))

        payees.sort()
        return payees
        
    def _read_ibnk_payee_id(self):
        self.select_links_frame_ibanking()
        self.current_frame_contains("Accounts")
        
        #click to show beneficiary page
        element = self._element_find("//*[@id='nav_ML281']", True, False)
        element.click()
        self.wait_until_page_contains("Maintain   Beneficiary")
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Fund Transfers")
        self.select_links_frame_ibanking()
        element = self._element_find("//*[@id='Maintain <br> Beneficiary']", True, False)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Add & Maintain Beneficiary")
        
        #click to show Account to Account Transfer Beneficiary
        element = self._element_find("//*[@id='pagePrintTag']/table/tbody/tr[3]/td/a", True, False)
        element.click()
        self.wait_until_page_contains("Account to Account Beneficiary")

        payees = []
        
        #Account to Account Beneficiary
        rows3 = self._element_find("//*[@id='pagePrintTag']/table/tbody/tr[@class='table_row_white']", False, False)
        self._info(len(rows3))
        
        if self._is_text_present("No Beneficiaries Available"):
            self._info("No Beneficiaries Available for OAT")
        else:
            for i in range(0, len(rows3)): #TODO
                account = rows3[i].find_elements_by_xpath("./td[1]")
                benefiname = rows3[i].find_elements_by_xpath("./td[3]")
                bankname = rows3[i].find_elements_by_xpath("./td[4]")
                currency = rows3[i].find_elements_by_xpath("./td[5]")
                self._info('%s> %s> %s> %s>' % (account[0].text, benefiname[0].text, bankname[0].text, currency[0].text))
                payees.append([account[0].text,
                                benefiname[0].text,
                                bankname[0].text,
                                currency[0].text])
            self._info(len(payees))

        self.select_links_frame_ibanking()
        element = self._element_find("//*[@id='Maintain <br> Beneficiary']", True, False)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Add & Maintain Beneficiary")
        
        #click to show Local Payment Transfer Beneficiary
        element = self._element_find("//*[@id='pagePrintTag']/table/tbody/tr[5]/td/a", True, False)
        element.click()
        self.wait_until_page_contains("Local Payment Transfer Beneficiaries")

        #Local Payment Transfer Beneficiary
        rows3 = self._element_find("//*[@id='pagePrintTag']/table/tbody/tr[@class='table_row_white']", False, False)
        self._info(len(rows3))
        
        if self._is_text_present("No Beneficiaries Available"):
            self._info("No Beneficiaries Available for LPT")
        else:
            for i in range(0, len(rows3)): #TODO
                account = rows3[i].find_elements_by_xpath("./td[1]")
                benefiname = rows3[i].find_elements_by_xpath("./td[3]")
                bankname = rows3[i].find_elements_by_xpath("./td[4]")
                currency = rows3[i].find_elements_by_xpath("./td[5]")
                self._info('%s> %s> %s> %s>' % (account[0].text, benefiname[0].text, bankname[0].text, currency[0].text))
                
                payees.append([account[0].text,
                                benefiname[0].text,
                                bankname[0].text,
                                currency[0].text])
            self._info(len(payees))
        
        self.select_links_frame_ibanking()
        element = self._element_find("//*[@id='Maintain <br> Beneficiary']", True, False)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Add & Maintain Beneficiary")
        
        #click to show Outward Telegraphic Transfer Beneficiary
        element = self._element_find("//*[@id='pagePrintTag']/table/tbody/tr[7]/td/a", True, False)
        element.click()
        self.wait_until_page_contains("Outward Telegraphic Transfer Beneficiary")
        
        #Outward Telegraphic Transfer Beneficiary
        rows3 = self._element_find("//*[@id='pagePrintTag']/table/tbody/tr[@class='table_row_white']", False, False)
        self._info(len(rows3))
        
        if self._is_text_present("No Beneficiaries Available"):
            self._info("No Beneficiaries Available IFT")
        else:
            for i in range(0, len(rows3)): #TODO
                account = rows3[i].find_elements_by_xpath("./td[1]")
                benefiname = rows3[i].find_elements_by_xpath("./td[2]")
                bankname = rows3[i].find_elements_by_xpath("./td[2]")
                currency = rows3[i].find_elements_by_xpath("./td[3]")
                self._info('%s> %s> %s> %s>' % (account[0].text, benefiname[0].text, bankname[0].text, currency[0].text))
                
                payees.append([account[0].text,
                                benefiname[0].text,
                                bankname[0].text,
                                currency[0].text])
            self._info(len(payees))
        return payees
                    
    def select_to_account(self, currency_cd):
        ''' Return selected account info by given currency.
        '''
        to_acct_xpath = "//div[@id='main']/div[@id='content']/div/dl/*"
        currency_cn = 'info-amount'
        acctName_cn = 'info-primary'
        acctNum_cn = 'info-secondary'
        to_acct_info = ''
        
        #self._synchronize()
        elements = self._element_find(to_acct_xpath, False, False)
        oat_list = self._find_OAT_list(elements)
       
        for acct in oat_list:
            temp_currency = acct.find_element_by_class_name(currency_cn).text
            account_link = acct.find_element_by_class_name(acctName_cn).text
            account_number = acct.find_element_by_class_name(acctNum_cn).text

            if currency_cd in temp_currency.strip():
                self._info("found %s %s" % (currency_cd, temp_currency))
                to_acct_info = (account_link + '\n' + account_number)
                acct.click()
                break
            
        return to_acct_info

        
    def _find_OAT_list(self, acct_list):
        flag = False
        acct_xpath = "//dd/ul/*"

        for element in acct_list:
            if flag == False:
                temp = element.find_element_by_link_text("My Accounts")
            if temp != None:
                if "My Accounts" == temp.text:
                    flag = True
                    temp = None
                    continue    
            if flag == True:
                oat_list = element.find_elements_by_xpath(acct_xpath)
                break
        
        return oat_list
            
    
    def select_from_account(self, currency_cd):
        ''' Return a list of selected account name and account info by given currency.
        '''
        
        from_acct_xpath = "//div[@class='list-view']/dl/dd/ul/*"
        
        from_list = self._element_find(from_acct_xpath, False, False)
        from_acct_list = []
        
        for acct in from_list:
            account = acct.find_element_by_class_name("info-amount")
            temp_currency = account.text
            account_name = acct.find_element_by_class_name("info-primary")
            account_number = acct.find_element_by_class_name("info-secondary")
            
            if currency_cd in temp_currency.strip():
                self._info("found %s %s" % (currency_cd, temp_currency))
                from_acct_info = (account_name.text + '\n' + account_number.text)
                from_acct_list.append(from_acct_info)
                from_acct_list.append(account_name.text)
                acct.click()
                break

        return from_acct_list

    def _synchronize(self, sync_ui=True, sync_ws=True, nodelay=False):
        """Wait until page is ready, i.e. application finished rendering and webservice requests are completed
        """
        self._debug("Entering to synchronize")
        if not nodelay:
            time.sleep(3)
        maxtries = 60
        while maxtries:
            maxtries -= 1
            UIisRendering, WSinProgress = self.execute_javascript(" try { return [ BreezeUIisRendering, BreezeWSinProgress ]; } catch (e) { return [ true, false ] } ")
            ui_ok = (not UIisRendering) if sync_ui else True
            ws_ok = (not WSinProgress) if sync_ws else True
            if ui_ok and ws_ok:
                self._debug("Leaving synchronize with %d tries left" % maxtries)
                return
            time.sleep(1.0)
        self._debug("Leaving synchronize by timeout")

    def get_transfer_date(self):
        ''' Used in make-transfer.tsv to get transafer date.
        '''
        return self._run('get_transfer_date')
            
    def _get_transfer_date_pk(self):
        date_list = []
        transfer_date_xpath = "//*[@id='TR_DT']"
        browser = self._current_browser()
        transfer_date = browser.find_element_by_xpath(transfer_date_xpath)
        date_temp = []

        date = transfer_date.text
        self._info(date)
        date = date.split("\n")[1]
        self._info(date)
        date_temp = date.split(',')
        date_list.append(date)
        date_list.append(date_temp[1].strip())
        
        return date_list

    def _get_transfer_date_hk(self):
        date_list = []
        transfer_date_xpath = "//*[@id='TR_DT']"
        browser = self._current_browser()
        transfer_date = browser.find_element_by_xpath(transfer_date_xpath)
        date_temp = []

        date = transfer_date.text
        self._info(date)
        date = date.split("\n")[1]
        self._info(date)
        date_temp = date.split(',')
        date_list.append(date)
        date_list.append(date_temp[1].strip())
        
        return date_list
    
    def _get_transfer_date_id(self):
        date_list = []
        transfer_date_xpath = "//*[@id='TR_DT']"
        browser = self._current_browser()
        transfer_date = browser.find_element_by_xpath(transfer_date_xpath)
        date_temp = []

        date = transfer_date.text
        self._info(date)
        date_temp = date.split(',')
        date_list.append(date)
        date_list.append(date_temp[1].strip())
        
        return date_list
    
    def _find_lastest_transaction_history(self):
        transfer_history_xpath = "//div[@class='list-view']/dl/*"
        browser = self._current_browser()
        history_list = self._element_finder.find(browser, transfer_history_xpath)
        today_flag = False
        result_his = history_list[0]

        for his in history_list:
            today_history = his.find_element_by_class_name("info-primary")
            today_his = today_history.text
            self._info("history text:" + today_his)
                
            if today_his == 'Today':
                today_flag = True
                continue

            if today_flag == True:
                self._info("find break here and end this function")
                result_his = his
                break

        return result_his

    def get_from_account_transfer_history(self):
        ''' Used in make-transfer.tsv to get tfrom account transfer history.
        
        In keyword of Verify Transfer History
        '''
        today_his_list = []
        today_his = self._find_lastest_transaction_history()
        from_acct = today_his.find_element_by_class_name("info-secondary").text
        self._info(from_acct)
        today_his_list.append(from_acct)
        today_amount = today_his.find_element_by_class_name("info-amount").text
        self._info(today_amount)
        today_his_list.append(today_amount)
        return today_his_list

    def get_from_account_transfer_history_by_name(self,from_account_name,from_amount):
        ''' Used in make-transfer.tsv to get tfrom account transfer history.
                In keyword of focus Account Name and Amount
        '''
        transfer_history_xpath = "//div[@class='list-view']/dl/*"
        browser = self._current_browser()
        history_list = self._element_finder.find(browser, transfer_history_xpath)
        today_flag = False
        exist_flag = False
        result_his = history_list[0]
        current_list=[]
        for his in history_list:
            today_history = his.find_element_by_class_name("info-primary")
            today_his = today_history.text
            self._info("history text:" + today_his)
                
            if today_his == 'Today':
                today_flag = True
                continue
            if today_his == 'Yesterday':
                today_flag = False
                break
            if today_flag == True and today_his=='Between Own Accounts':
                self._info("find 'Between Own Accounts' and continue this function")
                current_list.append(his)
                continue

            
        for his in current_list:
            current_from_account = his.find_element_by_class_name("info-secondary")
            current_account = current_from_account.text
            self._info("current:" + current_account)
            current_amount = his.find_element_by_class_name("info-amount").text
            self._info("current_amount:" + current_amount)    
            if current_account == from_account_name and current_amount=='PKR'+from_amount+'0':
                exist_flag = True
                return True
                continue

            
        return False

        
    def click_current_transfer_history(self):
        ''' Used in make-transfer.tsv to get current transfered transaction history.
        
        In keyword of Verify Transfer History Detail
        '''
        today_his = self._find_lastest_transaction_history()
        transfer_type = today_his.find_element_by_class_name("info-primary")
        transfer_type.click()

    def click_current_transfer_history_by_name(self,from_account_name,from_amount):
        ''' Used in make-transfer.tsv to get current transfered transaction history.
        
        In keyword of Verify Transfer History Detail
        '''
        transfer_history_xpath = "//div[@class='list-view']/dl/*"
        browser = self._current_browser()
        history_list = self._element_finder.find(browser, transfer_history_xpath)
        today_flag = False
        exist_flag = False
        result_his = history_list[0]
        current_list=[]
        for his in history_list:
            today_history = his.find_element_by_class_name("info-primary")
            today_his = today_history.text
            self._info("history text:" + today_his)
                
            if today_his == 'Today':
                today_flag = True
                continue
            if today_his == 'Yesterday':
                today_flag = False
                break
            if today_flag == True and today_his=='Between Own Accounts':
                self._info("find break here and end this function")
                current_list.append(his)
                continue

            
        for his in current_list:
            current_from_account = his.find_element_by_class_name("info-secondary")
            current_account = current_from_account.text
            self._info("current:" + current_account)
            current_amount = his.find_element_by_class_name("info-amount").text
            self._info("current_amount:" + current_amount)    
            if current_account == from_account_name:
                exist_flag = True
                today_his_but=his
                break
        transfer_type = today_his_but.find_element_by_class_name("info-primary")
        transfer_type.click()


        
#below keywords are not used in any robot cases. Just try out for whether the keyword call can be parametered. from current results, it cannot be. currently use "if" condition   
    def _ibnk_page_turning_pk(self, rows4Xpath, pagecount, pageXpath, singlepagecall):
        
        transactions1 = []
        temp = [] 
        
        rows4 = self._element_find(rows4Xpath, False, False)
        self._info(len(rows4))
        
        if int(pagecount) > 1:
            if singlepagecall == "_read_ibnk_account_transaction_pk_single_page":
                temp = self._read_ibnk_account_transaction_pk_single_page(rows4, len(rows4))#see here, cannot make the keyword parameterd. only can be judged by if confidition.
            elif singlepagecall == "_read_ibnk_account_scheduled_transaction_pk_single_page":
                temp = self._read_ibnk_account_scheduled_transaction_pk_single_page(rows4, len(rows4))
            else:
                pass
            transactions1 = transactions1 + temp
            
            for k in range(1, int(pagecount)):
                if k == 1:
                    element = self._element_find(pageXpath+"[" + str(k) + "]", True, False)
                else:
                    element = self._element_find(pageXpath+"[" + str(k + 2) + "]", True, False)
                element.click()
                self.wait_until_page_contains(str(k + 1) + " of " + str(pagecount) + " page(s).")
                
                rows4 = self._element_find(rows4Xpath, False, False)
                
                if singlepagecall == "_read_ibnk_account_transaction_pk_single_page":
                    temp = self._read_ibnk_account_transaction_pk_single_page(rows4, len(rows4))
                elif singlepagecall == "_read_ibnk_account_scheduled_transaction_pk_single_page":
                    temp = self._read_ibnk_account_scheduled_transaction_pk_single_page(rows4, len(rows4))
                else:
                    pass
                
                transactions1 = transactions1 + temp
            
        elif int(pagecount) == 1:
            if singlepagecall == "_read_ibnk_account_transaction_pk_single_page":
                temp = self._read_ibnk_account_transaction_pk_single_page(rows4, len(rows4))
            elif singlepagecall == "_read_ibnk_account_scheduled_transaction_pk_single_page":
                temp = self._read_ibnk_account_scheduled_transaction_pk_single_page(rows4, len(rows4))
            else:
                pass
            transactions1 = transactions1 + temp
        else:
            pass
        return transactions1
    
    def transaction_pk(self):   
        '''This is a try out. Used to verify whether the keyword call can be parametered. From my try, it cannot be. 
        Only can be parametered and then compared with if condition to verify which keyword you want to call.
        
        See _ibnk_page_turning_pk please.
        '''
        #click to show the first account's transaction
        element = self._element_find("//*[@id='printContent']/table/tbody/tr[5]/td[1]/table[1]/tbody/tr[2]/td[2]/a", True, False)
        self._info(element)
        element.click()
        self.wait_until_page_contains("Account transactions shown")
               
        #total page for transaction records Total: 44,1 of 3 page(s).
        if self._is_text_present("No Transaction Available"):
            self._info("No Beneficiaries Available IFT")
        else:
            #find page no for the transaction
            element = self._element_find("//*[@id='printContent']/table[2]/tbody/tr/td", False, False)
            self._info(element[0].text)
            
            #total page for transaction records Total: 44,1 of 3 page(s).
            pagecount = element[0].text.split(" ")[3]
            rows4Xpath = "//*[@id='vAcctTrxnList']/tbody/tr"
            pageXpath = "//*[@id='ignorePrint_paging']/tbody/tr/td/a"
            singlepagecall = "_read_ibnk_account_transaction_pk_single_page"#see here, keyword call
            self._info(singlepagecall)
            
            transactions = self._ibnk_page_turning_pk(rows4Xpath, pagecount, pageXpath, singlepagecall)              
        return transactions
    
    
    def add(self, first, second):   
        return int(first)+int(second)

    def select_to_others_account(self, bankname):
        ''' Return selected account info by given bankname.
        '''
        element = self._element_find("//*[@id='IBFT']/a", True, False)
        element.click()
        self.wait_until_page_contains_element("//dt[@id='IBFT']/following-sibling::dd/ul/li")

        other_acct_xpath = "//dt[@id='IBFT']/following-sibling::dd/ul/li"
        ibft_list = self._element_find(other_acct_xpath, False, False)

        to_acct_info = ''
        for acct in ibft_list:
            account = acct.find_element_by_xpath("./a/span[1]")
            temp_bankname = acct.find_element_by_xpath("./a/span[2]")
            acct_number = acct.find_element_by_xpath("./a/span[3]")

            if bankname in temp_bankname.text.strip():
                self._info("found %s %s" % (bankname, temp_bankname.text))
                to_acct_info = (account.text + '\n' + acct_number.text)
                acct.click()
                break

        return to_acct_info
